package com.hugh.glrpcprovider.config;

import com.hugh.commom.netty.server.NettyServerStart;
import com.hugh.commom.util.NetworkUtils;
import com.hugh.commom.zk.client.entity.ZkNodeEntity;
import com.hugh.commom.zk.client.ZkRpcHandle;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: Hugh
 * @Date: 2020/6/13
 */
@Component
@Slf4j
public class ServiceBeanConfig implements ApplicationListener<ContextRefreshedEvent>{

    private Map<String, Object> processMapping = new ConcurrentHashMap<String, Object>();

    @Value("${netty.server.port:8001}")
    private Integer port;

    @Autowired
    private ZkRpcHandle zkUtil;

    //注册的zk路径 /rpc/org.apache.dubbo.demo.DemoService/providers/ip
    //key: org.apache.dubbo.demo.DemoService , val: ip
    @SneakyThrows
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        if(Objects.nonNull(applicationContext)){
            Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Service.class);
            processMapping = beansWithAnnotation;
            //构建注册信息并进行注册
            buildZkINfo(beansWithAnnotation);
            new NettyServerStart().startWithPort(port, beansWithAnnotation);
        }
    }


    private Map<String, ZkNodeEntity> buildZkINfo(Map<String, Object> beansWithAnnotation) throws Exception {
        Map<String, ZkNodeEntity> resMap = new HashMap<>();
        for(Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()){
            resMap.put(entry.getKey(), ZkNodeEntity.builder().ip(NetworkUtils.getLocalIP()).port(port).rt(0L).build());
        }
        zkUtil.regist(resMap);
        return resMap;
    }
}
